import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/team/soccer/zq_team_detail_logic.dart';
import 'package:sports_new/controller/team/soccer/zq_team_lineup_logic.dart';
import 'package:sports_new/entity/team/zq_team_lineup_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';

import '../../../widgets/base/qkd_text.dart';

class ZqTeamLineupView extends StatefulWidget {
  const ZqTeamLineupView({super.key, required this.teamId});
  final int teamId;

  @override
  State<ZqTeamLineupView> createState() => _ZqTeamLineupViewState();
}

class _ZqTeamLineupViewState extends State<ZqTeamLineupView> {
  late final ZqTeamLineupLogic logic =
      Get.put(ZqTeamLineupLogic(), tag: widget.teamId.toString());
  late final ZqTeamDetailLogic teamLogic =
      Get.find<ZqTeamDetailLogic>(tag: widget.teamId.toString());
  @override
  Widget build(BuildContext context) {
    return GetBuilder<ZqTeamLineupLogic>(
        initState: (state) => logic.requestData(widget.teamId),
        tag: widget.teamId.toString(),
        builder: (controller) {
          return LoadingWidget<bool>(
            isLoading: controller.isLoading,
            data:
                controller.data.every((element) => element.player?.length == 0),
            child: () => Container(
              color: Colours.greyF7,
              child: ListView.builder(
                  physics: const ClampingScrollPhysics(),
                  itemCount: controller.data.length,
                  padding: const EdgeInsets.only(left: 8, right: 8),
                  itemBuilder: (BuildContext context, int index) =>
                      _listItem(index).paddingOnly(
                          bottom:
                              controller.data.length == index + 1 ? 50 : 0)),
            ),
          );
        });
  }

  Widget _listItem(itemIndex) {
    return logic.data[itemIndex].player == null ||
            logic.data[itemIndex].player?.length == 0
        ? Container()
        : Padding(
            padding: const EdgeInsets.only(top: 8),
            child: Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8), color: Colours.white),
              child: Padding(
                  padding: const EdgeInsets.only(
                      bottom: 8, top: 16, left: 12, right: 12),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _playerItems(logic.data[itemIndex]),
                      _priceItems(logic.data[itemIndex], itemIndex)
                    ],
                  )),
            ),
          );
  }

  Widget _playerItems(ZqTeamLineupEntity? entity) {
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      QkdText(entity?.title ?? "", fontSize: 16,fontWeight: FontWeight.w500),
      Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: List.generate(entity?.player?.length ?? 0,
              (index) => _player(entity?.player?[index])))
    ]);
  }

  Widget _priceItems(ZqTeamLineupEntity? entity, int index) {
    String price = "";
    if (entity?.player?.any((element) => !element.value.noValue) == true) {
      if (index == 0 ||
          (teamLogic.data?.type != "1" && teamLogic.data?.type != "2")) {
        price = "身价(英镑)";
      } else {
        price = "俱乐部/身价(英镑)";
      }
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        QkdText(price, fontSize: 12,color: Colours.grey666666),
        Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: List.generate(
              entity?.player?.length ?? 0,
              (index) => Container(
                  height: 50,
                  alignment: Alignment.centerRight,
                  child: _price(entity?.player?[index], price == "")
              )
          ),
        )
      ],
    );
  }

  Widget _player(Player? player) {
    return SizedBox(
      height: 50,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          CachedNetworkImage(
            height: 32,
            width: 24,
            fit: BoxFit.cover,
            imageUrl: player?.photo ?? "",
            placeholder: (context, url) => Styles.placeholderIcon(),
            errorWidget: (context, url, error) => Image.asset(
              Utils.getImgPath('zq_placeholder.png'),
              height: 32,
              width: 24,
            ),
          ),
          Container(width: 8),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Flexible(
                  child: QkdText(player?.playerCn ?? "",fontSize: 13)),
              if ((player?.number != null && player?.number != ""
                          ? "${player!.number}号\u2000"
                          : "") +
                      (player?.age != null && player?.age != ""
                          ? "${player!.age}岁\u2000"
                          : "") +
                      (player?.countryCn != null &&
                              player?.countryCn != "" &&
                              (teamLogic.data?.nameChs != player?.countryCn)
                          ? "${player?.countryCn}"
                          : "") !=
                  "")
                QkdText(
                    (player?.number != null && player?.number != ""
                            ? "${player!.number}号\u2000"
                            : "") +
                        (player?.age != null && player?.age != ""
                            ? "${player!.age}岁\u2000"
                            : "") +
                        (player?.countryCn != null &&
                                player?.countryCn != "" &&
                                (teamLogic.data?.nameChs != player?.countryCn)
                            ? "${player?.countryCn}"
                            : ""),
                    fontSize: 11,color: Colours.grey66
                )
            ],
          )
        ],
      ),
    );
  }

  Widget _price(Player? player, bool toNull) {
    if (toNull) {
      return QkdText("");
    } else if ((player?.teamCn == null || player?.teamCn == "") &&
        (player?.value.noValue == true ||
            double.parse(player?.value ?? "0") == 0)) {
      return QkdText("-", fontSize: 13);
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          player?.type == 1 || player?.type == 2
              ? player?.place == "主教练"
                  ? Container()
                  : QkdText(player?.teamCn ?? "-",
                      fontSize: 11,fontWeight: FontWeight.w500,
                      textAlign: TextAlign.center)
              : Container(),
          QkdText(
            player?.value != null &&
                  player?.value != "" &&
                  double.parse(player?.value ?? "0") > 0
              ? "${player!.value}万" : "-",
            fontSize: 13
          ),
        ],
      );
    }
  }
}
